import { Slot, component$, createContextId, useContextProvider, useSignal, useStyles$, useVisibleTask$ } from '@builder.io/qwik'
import type { IMenu, IMenuState } from './types';
import styles from './index.css?inline';
import { generateUUID } from '~/utils';
import { useState } from './useState';

export const menuContextId = createContextId<IMenuState>(generateUUID())

const Menu = component$<IMenu>((props) => {
    useStyles$(styles)
    const { theme = 'dark', width, mode = 'horizontal', className, collapse, collapseWidth } = props;
    const collapseDone = useSignal<boolean>(false);
    useVisibleTask$(({ track }) => {
        track(() => props.collapse)
        if (collapse) {
            setTimeout(() => {
                collapseDone.value = true;
            }, props.duration || 300)
        } else {
            collapseDone.value = false;
        }
    })

    const [store] = useState(props)

    useContextProvider(menuContextId, store)
    return (
        <ul
            class={[
                `qrui-menu`,
                `qrui-menu-${theme}`,
                "qrui-menu qrui-menu-root transition-all ease-linear h-full flex flex-1 justify-start", `qrui-menu-mode-${mode}`, {
                    "flex-col": mode === 'vertical',
                    "flex-row": mode === 'horizontal',
                    'qrui-menu-collapse': collapse,
                    'qrui-menu-collapse-done': collapseDone.value,
                },
                className,
            ]}
            style={{
                width: (collapse ? collapseWidth : width) || '100%',
                transitionDuration: `${props.duration || 300}ms`
            }}
        >
            <Slot />
        </ul>
    )
})

export default Menu;